package com.jxs.android.ges;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;

import com.jxs.android.ges.data.UserInfo;
import com.jxs.android.ges.data.WorkLogInfo;
import com.jxs.android.soap.BuWebService;
import com.jxs.android.soap.IWebService;
import com.jxs.android.soap.SoapUtil;
import com.jxs.android.util.HandlerHolder;
import com.jxs.android.util.MemoryUtil;
import com.jxs.android.util.Timer;
import com.jxs.android.weiget.BuAlertDailog;
import com.jxs.android.weiget.BuLoadingDailog;
import com.jxs.android.weiget.TopBar;
import com.jxs.android.weiget.WorkLogCommentItem;
import com.jxs.android.weiget.WorkLogEditItem;
import com.jxs.android.weiget.WorkLogEditSubTitle;

@SuppressLint("HandlerLeak")
public class WorkLogEdit extends AbstractActivity implements WorkLogDetailManager.UI {

	private BuLoadingDailog progressDialog;
	private ViewHolder detailViewHolder;
	private String wl_id = "";
	private TopBar topBar;
	private LinearLayout bu_common_extends_detail;
	private LinearLayout bu_common_extends_todayList;
	private LinearLayout bu_common_extends_tomorrowList;
	private LinearLayout bu_common_extends_commentList;
	private WorkLogEditSubTitle todayListBar;
	private WorkLogEditSubTitle tomorrowListBar;
	private WorkLogEditSubTitle commentListBar;
	private Context context;
	private WorkLogInfo workLogInfo;

	private WorkLogCommentItem commentListBarItem;

	private WorkLogSaveHolder workLogSaveHolder;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		context = this;
		initTopBar(savedInstanceState, R.layout.bu_work_log_detail);
		bu_common_extends_detail = (LinearLayout) findViewById(R.id.bu_common_extends_detail);
		bu_common_extends_todayList = (LinearLayout) findViewById(R.id.bu_common_extends_todayList);
		bu_common_extends_tomorrowList = (LinearLayout) findViewById(R.id.bu_common_extends_tomorrowList);
		bu_common_extends_commentList = (LinearLayout) findViewById(R.id.bu_common_extends_commentList);
		bu_common_extends_commentList.setVisibility(View.GONE);
		InitViewHolder initViewHolder = new InitViewHolder(this);
		detailViewHolder = initViewHolder.init();
		bu_common_extends_detail.removeAllViews();
		bu_common_extends_detail.addView(initViewHolder.getView());
		if (null != getIntent() && null != getIntent().getExtras()) {
			wl_id = getIntent().getExtras().getString("wl_id");
			loadingWorkLogInfo();
		}
		initHolder();
		initSubBar();
	}

	private void initHolder() {
		workLogSaveHolder = new WorkLogSaveHolder(handler, wl_id);
	}

	private void initSubBar() {
		todayListBar = (WorkLogEditSubTitle) findViewById(R.id.todayList_bar);
		tomorrowListBar = (WorkLogEditSubTitle) findViewById(R.id.tomorrowList_bar);
		commentListBar = (WorkLogEditSubTitle) findViewById(R.id.commentList_bar);

		commentListBar.setVisibility(View.GONE);
		commentListBarItem = (WorkLogCommentItem) findViewById(R.id.commentList_bar_item);
		commentListBarItem.setVisibility(View.GONE);

		todayListBar.setAddOptionListen(todayListBarListen);
		tomorrowListBar.setAddOptionListen(tomorrowListBarListen);
		commentListBar.setAddOptionListen(commentListBarListen);
	}

	private WorkLogEditSubTitle.AddOptionListen todayListBarListen = new WorkLogEditSubTitle.AddOptionListen() {

		@Override
		public void logic(View v) {
			addTodayAndTomorrowListItem();
		}
	};

	private void addTodayAndTomorrowListItem() {
		WorkLogEditItem todayItm = new WorkLogEditItem(context, todayListWorkLogEditItems.size() + 1);
		todayItm.setValue("", "");
		todayListWorkLogEditItems.add(todayItm);
		bu_common_extends_todayList.addView(todayItm);

		WorkLogEditItem tomorrowItem = new WorkLogEditItem(context, tomorrowListWorkLogEditItems.size() + 1);
		tomorrowItem.setValue("", "");
		tomorrowListWorkLogEditItems.add(tomorrowItem);
		bu_common_extends_tomorrowList.addView(tomorrowItem);
	}

	private WorkLogEditSubTitle.AddOptionListen tomorrowListBarListen = new WorkLogEditSubTitle.AddOptionListen() {

		@Override
		public void logic(View v) {
			addTodayAndTomorrowListItem();
		}
	};
	private WorkLogEditSubTitle.AddOptionListen commentListBarListen = new WorkLogEditSubTitle.AddOptionListen() {

		@Override
		public void logic(View v) {
			WorkLogCommentItem child = new WorkLogCommentItem(context, commentListWorkLogCommentItems.size() + 1);
			child.setNewCreat(true);
			child.setValue("", GesApplication.getUserInfo().getName(), Timer.getSDFyyMMddHHmmss().format(System.currentTimeMillis()));
			commentListWorkLogCommentItems.add(child);
			bu_common_extends_commentList.addView(child);
			// commentListBar.showAdd(false);// 增加一条点评之后隐藏
		}
	};

	@Override
	public void topBarLogic(TopBar topBar) {
		this.topBar = topBar;
		// SpinnerButton FilterView Button
		topBar.setSpinnerBtnText("保存");
		super.topBarReturn(topBar);
		topBar.showAllBtn();
		topBar.hindFilter();
		topBar.hindLogicBtn();
		topBar.setTitle("工作日志修改");
		this.topBar.setBtnListern(btnListern);
	}

	/**
	 * 修改
	 * 
	 * @param todayListWorkLogEditItems
	 * @param tomorrowListWorkLogEditItems
	 */
	private void update(List<WorkLogEditItem> todayListWorkLogEditItems, List<WorkLogEditItem> tomorrowListWorkLogEditItems) {
		workLogSaveHolder.saveWorkLog(GesApplication.getUserInfo().getTicket(), workLogInfo.create_date, todayListWorkLogEditItems, tomorrowListWorkLogEditItems);
	}

	private TopBar.BtnListern btnListern = new TopBar.BtnListern() {

		@Override
		public void onSpinnerBtn() {// 修改

			if (todayListWorkLogEditItems.size() == 0 && tomorrowListWorkLogEditItems.size() == 0) {
				errorMsgPop("未作计划无需修改");
				return;
			}

			progressDialog.show();
			update(todayListWorkLogEditItems, tomorrowListWorkLogEditItems);
		}

		@Override
		@Deprecated
		public void onLogicBtn() {// 点评
		}

		@Override
		@Deprecated
		public void onFilterBtn() {// 删除
		}
	};

	private void loadingWorkLogInfo() {
		progressDialog = new BuLoadingDailog(this);
		progressDialog.showLoading(R.string.load_and_wait);
		new Thread(new Runnable() {
			@Override
			public void run() {
				getWorkLogDetail(GesApplication.getUserInfo().getTicket(), wl_id);
			}
		}).start();
	}

	private void getWorkLogDetail(String ticket, String wl_id) {
		// 2.4.3 getWorkLogDetail 【获取工作日志详单接口】
		String wsdl_url = GesApplication.WSDL_URL;// wsdl
		String namespace = GesApplication.WSDL_NAME_SPACE;// namespace
		String methodName = "getWorkLogDetail";// 要调用的方法名称
		SoapObject request = new SoapObject(namespace, methodName);
		request.addProperty("ticket", ticket);
		request.addProperty("wl_id", wl_id);
		BuWebService webService = new BuWebService(wsdl_url, request);
		webService.setDoNet(false);
		webService.requestWSDL(new IWebService() {
			@Override
			public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
				SoapObject response = (SoapObject) envelope.getResponse();
				paser(response);
			}

			@Override
			public void error(String message, Exception e) {
				Message msg = new Message();
				msg.what = HandlerHolder.What.ERROR_MSG;
				msg.obj = message;
				handler.sendMessage(msg);
			}

		});
	}

	private void paser(SoapObject soapObject) {
		if (null != soapObject) {
			String stauts = soapObject.getProperty("status").toString();
			SoapObject msgObjec = (SoapObject) soapObject.getProperty("msg");
			String message = msgObjec.getProperty("message").toString();
			if ("-2".equals(stauts)) {
				Message msg = new Message();
				msg.what = HandlerHolder.What.ERROR_MSG;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("-1".equals(stauts)) {
				Message msg = new Message();
				msg.what = HandlerHolder.What.TO_LOGIN;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("0".equals(stauts)) {

				UserInfo info = GesApplication.getUserInfo();
				info.setWlCanDelete(Boolean.valueOf(soapObject.getProperty("canDelete").toString()));
				info.setWlCanDoComment(Boolean.valueOf(soapObject.getProperty("canDoComment").toString()));
				info.setWlCanUpdate(Boolean.valueOf(soapObject.getProperty("canUpdate").toString()));

				// (6)detail:工作日期详情[单条内容]
				SoapObject detail = (SoapObject) soapObject.getProperty("detail");
				// (7)todayList:今日工作列表[多条内容]
				SoapObject todayList = (SoapObject) soapObject.getProperty("todayList");
				// (8)tomorrowList:昨日计划列表[多条内容]
				SoapObject tomorrowList = (SoapObject) soapObject.getProperty("tomorrowList");
				// (9)commentList:点评列表[多条内容]
				SoapObject commentList = (SoapObject) soapObject.getProperty("commentList");

				Map<String, SoapObject> res = new HashMap<String, SoapObject>();
				res.put("detail", detail);
				res.put("todayList", todayList);
				res.put("tomorrowList", tomorrowList);
				res.put("commentList", commentList);

				Message msg = new Message();
				msg.what = HandlerHolder.What.UPDATE_LIST_UI;
				msg.obj = res;

				handler.sendMessage(msg);
			}
		}
	}

	private Handler handler = new Handler() {

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			if (!MemoryUtil.isCurrentActivity(WorkLogEdit.class)) {
				return;
			}
			if (null != progressDialog && progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
			if (msg.what == HandlerHolder.What.UPDATE_LIST_UI) {

				UserInfo info = GesApplication.getUserInfo();
				/**
				 * @topBar.setSpinnerBtnText("修改");
				 * @topBar.setFilterBtnText("删除");
				 * @topBar.setLogicBtnText("点评");
				 */
				if (!info.isWlCanUpdate()) {
					topBar.hindSpinnerBtn();
					todayListBar.showAdd(false);
					tomorrowListBar.showAdd(false);
				}
				if (!info.isWlCanDelete()) {
					topBar.hindFilter();
				}
				if (!info.isWlCanDoComment()) {
					topBar.hindLogicBtn();
					commentListBar.setEnabled(false);
				}

				Map<String, SoapObject> res = (Map<String, SoapObject>) msg.obj;
				updateDetail(res.get("detail"));
				updateTodayList(res.get("todayList"));
				updateTomorrowList(res.get("tomorrowList"));
				updateCommentList(res.get("commentList"));
			} else if (msg.what == HandlerHolder.What.ERROR_MSG) {
				errorMsgPop(msg.obj.toString());
			} else if (msg.what == HandlerHolder.What.TO_LOGIN) {
				errorMsgToLogin(msg.obj.toString());
			} else if (msg.what == HandlerHolder.What.WORK_LOG_SAVE_RESLT_OK) {
				show(wl_id, "修改成功！");
			}
		}
	};

	final int REQ_GET_SMS_CONTENT = 0xcba001;
	final int REQ_EDIT = 0xcba002;

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQ_GET_SMS_CONTENT && resultCode == RESULT_OK) {
			finish();
		}
	}

	private void show(final String wl_id, final String message) {

		BuAlertDailog.builder(context, "提示", message, new BuAlertDailog.AlertOkAndCancelListener() {

			@Override
			public void okLogic(Dialog dialog) {
				dialog.cancel();
				Intent intent = new Intent(context, WorkLogGetSmsContent.class);
				Bundle bundle = new Bundle();
				bundle.putString("wl_id", wl_id);
				intent.putExtras(bundle);
				startActivityForResult(intent, REQ_GET_SMS_CONTENT);
			}

			@Override
			public String getOkText(Context context) {
				return "发送短信";
			}

			@Override
			public String getCancleText(Context context) {
				return getString(R.string.prompt_cancel);
			}

			@Override
			public void cancelLogic(Dialog dialog) {
				dialog.cancel();
				setResult(RESULT_OK);
				finish();
			}
		}).show();

	}

	private List<WorkLogEditItem> todayListWorkLogEditItems = new ArrayList<WorkLogEditItem>();

	private void updateTodayList(SoapObject todayList) {

		UserInfo userInfo = GesApplication.getUserInfo();

		if (null != todayList) {
			for (int i = 0; i < todayList.getPropertyCount(); i++) {
				SoapObject taskBeanObject = (SoapObject) todayList.getProperty(i);
				String contentStr = SoapUtil.getValue(taskBeanObject, "content");
				String noteStr = SoapUtil.getValue(taskBeanObject, "remark");

				WorkLogEditItem child = new WorkLogEditItem(this, i + 1);
				if (!userInfo.isWlCanUpdate()) {
					child.setEable(false);
				}
				child.setValue(contentStr, noteStr);
				todayListWorkLogEditItems.add(child);
				bu_common_extends_todayList.addView(child);
			}
		}

	}

	private List<WorkLogEditItem> tomorrowListWorkLogEditItems = new ArrayList<WorkLogEditItem>();

	private void updateTomorrowList(SoapObject tomorrowList) {
		UserInfo userInfo = GesApplication.getUserInfo();
		if (null != tomorrowList) {
			for (int i = 0; i < tomorrowList.getPropertyCount(); i++) {
				SoapObject taskBeanObject = (SoapObject) tomorrowList.getProperty(i);
				String contentStr = SoapUtil.getValue(taskBeanObject, "content");
				String noteStr = SoapUtil.getValue(taskBeanObject, "remark");

				WorkLogEditItem child = new WorkLogEditItem(this, i + 1);
				if (!userInfo.isWlCanUpdate()) {
					child.setEable(false);
				}
				child.setValue(contentStr, noteStr);
				tomorrowListWorkLogEditItems.add(child);
				bu_common_extends_tomorrowList.addView(child);
			}
		}
	}

	private List<WorkLogCommentItem> commentListWorkLogCommentItems = new ArrayList<WorkLogCommentItem>();

	private void updateCommentList(SoapObject commentList) {
		if (null != commentList) {
			for (int i = 0; i < commentList.getPropertyCount(); i++) {
				SoapObject taskBeanObject = (SoapObject) commentList.getProperty(i);
				String contentStr = SoapUtil.getValue(taskBeanObject, "content");
				String staff_name = SoapUtil.getValue(taskBeanObject, "staff_name");
				// String staff_no = SoapUtil.getValue(taskBeanObject,
				// "staff_no");
				String comment_date = SoapUtil.getValue(taskBeanObject, "comment_date");

				WorkLogCommentItem child = new WorkLogCommentItem(this, i + 1);
				child.setValue(contentStr, staff_name, comment_date);
				commentListWorkLogCommentItems.add(child);
				bu_common_extends_commentList.addView(child);
			}
		}

	}

	private WorkLogInfo paserDetailInfo(SoapObject taskBeanObject) {
		WorkLogInfo workLogInfo = new WorkLogInfo();
		workLogInfo.wl_id = SoapUtil.getValue(taskBeanObject, "wl_id");
		workLogInfo.create_date = SoapUtil.getValue(taskBeanObject, "create_date");
		workLogInfo.update_date = SoapUtil.getValue(taskBeanObject, "update_date");
		workLogInfo.staff_name = SoapUtil.getValue(taskBeanObject, "staff_name");
		workLogInfo.staff_no = SoapUtil.getValue(taskBeanObject, "staff_no");
		workLogInfo.today_content = SoapUtil.getValue(taskBeanObject, "today_content");
		workLogInfo.week_desc = SoapUtil.getValue(taskBeanObject, "week_desc");
		workLogInfo.industry_type_name = SoapUtil.getValue(taskBeanObject, "industry_type_name");
		return workLogInfo;
	}

	private void updateDetail(SoapObject detail) {
		workLogInfo = paserDetailInfo(detail);
		detailViewHolder.staff_name.setText(workLogInfo.staff_name);// 工号
		detailViewHolder.industry_type_name.setText(workLogInfo.industry_type_name);// 工号
		detailViewHolder.create_date.setText(workLogInfo.create_date + "\n" + workLogInfo.week_desc);// 姓名
		detailViewHolder.create_date.setBackgroundResource(R.drawable.transparent);
		detailViewHolder.update_date.setText(workLogInfo.update_date);// 分公司
	}

}
